<?php
/**
 * @title 94. 二叉树的中序遍历 - 栈优化
 * @author start2004
 */


class Solution {

    /**
     * @param TreeNode $root
     * @return Integer[]
     */
    function inorderTraversal($root) {
        /**
         * @since 2020-07-30 结果集
         */
        $result = [];

        /**
         * @since 2020-07-30 栈
         */
        $stacks = [];

        /**
         * @since 2020-07-30 处理栈数据
         */
        do{
            /**
             * @since 2020-07-30 非子树
             */
            if(gettype($root) !== "object"){
                $result[] = $root;

                /**
                 * @since 2020-07-30 出栈一个新root
                 */
                $root = array_pop($stacks);
            } else {
                /**
                 * @since 2020-07-30 左子树 !null
                 */
                if($root->left !== null){
                    if($root->right !== null){
                        $stacks[] = $root->right;
                    } else {}
                    $stacks[] = $root->val;

                    /**
                     * @since 2020-07-30 右子树作为下次root, 避免入栈出栈
                     */
                    $root = $root->left;
                } else {
                    $result[] = $root->val;

                    /**
                     * @since 2020-07-30 右子树 !null
                     * @since 2020-07-30 右子树作为下次root, 避免入栈出栈
                     */
                    if($root->right !== null){
                        $root = $root->right;
                    } else {
                        /**
                         * @since 2020-07-30 出栈新root
                         */
                        $root = array_pop($stacks);
                    }
                }
            }
        }while($root !== null);

        /**
         * @return
         */
        return $result;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.30_8.php
 */
$datas = [
    [1,null,2,3],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->inorderTraversal($xhprof->tree($data));
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
